package Cantella::DJabberd::Web::Model::Admin;

use metaclass 'Reaction::Meta::Class';
use Reaction::Class;
use Catalyst::Utils;
use Scalar::Util ();

use Cantella::DJabberd::Store;
use Cantella::DJabberd::Model::Admin;

class Admin is 'Reaction::Object', is 'Catalyst::Component', which {

  has _schema => ( is => 'ro', isa => 'Cantella::DJabberd::Store', required => 0);

  implements 'COMPONENT' => as {
    my ($class, $app, $args) = @_;
    my %cfg = %{ Catalyst::Utils::merge_hashes($class->config, $args) };
    my $params = $cfg{db_params} || {};
    my $schema = Cantella::DJabberd::Store->connect($cfg{db_dsn}, $cfg{db_user}, $cfg{db_password}, $params);

    my $self = $class->new(_schema => $schema);
    $app->log->debug(" NEW HAPPENED ");
    confess "$schema" unless $self->_has_schema;
    return $self;
  };

  implements ACCEPT_CONTEXT => as {
    my ($self, $ctx) = @_;
    return $self->CONTEXTUAL_CLONE($ctx) unless ref $ctx;
    return $ctx->stash->{ref($self)} ||= $self->CONTEXTUAL_CLONE($ctx);
  };

  implements CONTEXTUAL_CLONE => sub {
    my $self = shift;
    my ($ctx) = @_;
    my $schema = $self->_schema;
    confess unless $self->_has_schema;
    $schema = $schema->clone;
    if (my $username = $ctx->session->{ref($self)}) {
      if(my $user = $schema->resultset('User')->find({ username => $username })){
        $schema->_set_current_user( $user );
      }
    }
    my $im = Cantella::DJabberd::Model::Admin->new(djabberd_schema => $schema);
    Scalar::Util::weaken($ctx);
    my $cb = sub {
      if(my $user = shift){
        $ctx->session->{ref($self)} = $user->username
      } else {
        delete $ctx->session->{ref($self)};
      }
    };
    $im->current_user_callback($cb);
    return $im;
  };
};

__PACKAGE__->config
  (
   db_dsn      => 'dbi:mysql:database=cantella_djabberd;host=10.0.7.4',
   db_user     => 'djabberd_test',
   db_password => 'test01',
   db_params   => { quote_char => '`', name_sep => '.' },
  );

1;
